package com.example.writting.ui.wordfill.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.databinding.ItemWordExplanationBinding
import com.example.writting.model.WordExplanation

class WordExplanationAdapter : RecyclerView.Adapter<WordExplanationAdapter.ViewHolder>() {
    private var items = listOf<WordExplanation>()
    private val expandedItems = mutableSetOf<Int>()

    fun updateItems(newItems: List<WordExplanation>) {
        items = newItems
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemWordExplanationBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items[position], position in expandedItems) { pos ->
            if (pos in expandedItems) {
                expandedItems.remove(pos)
            } else {
                expandedItems.add(pos)
            }
            notifyItemChanged(pos)
        }
    }

    override fun getItemCount() = items.size

    class ViewHolder(private val binding: ItemWordExplanationBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: WordExplanation, isExpanded: Boolean, onClick: (Int) -> Unit) {
            binding.wordText.text = item.word
            binding.explanationText.text = item.explanation
            
            if (item.examples != null) {
                binding.root.setOnClickListener { onClick(adapterPosition) }
                binding.examplesLayout.visibility = if (isExpanded) View.VISIBLE else View.GONE
                binding.examplesLayout.removeAllViews()
                item.examples.forEach { example ->
                    val exampleView = LayoutInflater.from(binding.root.context)
                        .inflate(android.R.layout.simple_list_item_1, binding.examplesLayout, false)
                    exampleView.findViewById<android.widget.TextView>(android.R.id.text1).text = example
                    binding.examplesLayout.addView(exampleView)
                }
                binding.expandIcon.visibility = View.VISIBLE
                binding.expandIcon.rotation = if (isExpanded) 180f else 0f
            } else {
                binding.expandIcon.visibility = View.GONE
                binding.examplesLayout.visibility = View.GONE
                binding.root.setOnClickListener(null)
            }
        }
    }
} 